<template>
  <div class="filter-container">
    <slot name="form">
      <template v-for="item of fields">
        <el-select
          v-if="item.type === 'list'"
          class="filter-item"
          v-model="searchForm[item.name]"
          :placeholder="item.label || '请选择'"
          clearable
          :key="item.name"
        >
          <el-option
            v-for="option in item.options"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>

        <el-input
          v-else-if="item.type === 'text'"
          class="filter-item"
          v-model="searchForm[item.name]"
          :placeholder="item.label || '请输入'"
          style="width: 200px;"
          @keyup.enter.native="handleSearch"
          clearable
          :key="item.name"
        />

        <el-input
          v-else
          class="filter-item"
          v-model="searchForm[item.name]"
          :placeholder="item.label || '请输入'"
          style="width: 200px;"
          @keyup.enter.native="handleSearch"
          clearable
          :key="item.name"
        />
      </template>
    </slot>

    <slot name="buttons">
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleAdd">新增</el-button>
    </slot>
  </div>
</template>
<script>
/***********
 * 参数
 * @param {Array<field>} fields 搜索表单配置列表
 * @param {object} fields[index] field
 *  { name: "表单 name", label: "选择 / 输入提示", initValue: "初始化值"
 *    type: "类型： text / list / ...", options: [] select options }
 *
 *    options: [{ value, label }]
 *
 * @event search 点击搜索的事件，传入整个搜索表单
 * @event add 点击新增按钮的事件
 *
 ***********/


export default {
  name: 'search-box',
  props: {
    fields: Array
  },
  data() {
    return {
      searchForm: {}
    };
  },
  created() {
    // 初始化表单值
    if (this.fields && this.fields.length) {
      const searchForm = {};
      for (const item of this.fields) {
        if ('initValue' in item) {
          searchForm[item.name] = item.initValue;
        }
      }
      this.searchForm = searchForm;
    }
  },
  methods: {
    // 获取搜索表单的值
    getSearchData() {
      const data = {};

      for (const { name } of this.fields) {
        data[name] = this.searchForm[name];
      }

      return data;
    },

    // 搜索，获取搜索表单
    handleSearch() {
      this.$emit('search', this.getSearchData());
    },

    // 点击新增按钮
    handleAdd() {
      this.$emit('add', this.getSearchData());
    }
  }
}
</script>
